package com.atmilan.quartz.utils.source;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.atmilan.quartz.constant.enums.BarCodeEnum;
import com.atmilan.quartz.constant.enums.CategoryTypeEnum;
import com.atmilan.quartz.constant.enums.ProductTypeEnum;
import com.atmilan.quartz.constant.enums.StockAreaTempEnum;
import com.atmilan.quartz.model.dto.crmeb.StoreProductCrmebRequest;
import com.atmilan.quartz.model.entity.buyer.Supplier;
import com.atmilan.quartz.model.entity.crmeb.CategoryMatch;
import com.atmilan.quartz.model.entity.crmeb.StoreBrand;
import com.atmilan.quartz.model.entity.crmeb.StoreProductAttr;
import com.atmilan.quartz.model.entity.jky.JkyProductSku;
import com.atmilan.quartz.model.entity.unibuy.UnibuyProduct;
import com.atmilan.quartz.model.entity.unibuy.UnibuyProductSku;
import com.atmilan.quartz.model.result.PriceResult;
import com.atmilan.quartz.service.ICategoryMatchService;
import com.atmilan.quartz.service.IStoreBrandService;
import com.atmilan.quartz.service.ISupplierService;
import com.atmilan.quartz.sync.push.crmeb.domain.StoreProductAttrValueRequest;
import com.atmilan.quartz.sync.push.crmeb.enums.CrmebMerchantEnums;
import com.atmilan.quartz.utils.PriceUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.util.StringUtil;

/**
 * 处理源数据转换和计算相关信息
 * @Description: 
 * @author daigb
 * @date 2021-03-05
 */
@Service
public class SourceUnibuyProductUtil {
    @Autowired
    IStoreBrandService storeBrandService;
    @Autowired
    ICategoryMatchService categoryMatchService;
    @Autowired
    ISupplierService supplierService;
    @Autowired
    PriceUtil priceUtil;

    /**
     * 构建DO对象
     * @Description:  
     * @author daigb 
     * @param @param product
     * @param @param productSkus
     * @param @return
     * @return StoreProductRequest
     * @throws
     */
    public StoreProductCrmebRequest buildCrmebProduct(UnibuyProduct product, List<UnibuyProductSku> skus, int stock,Supplier supplier) {
        StoreProductCrmebRequest productRequest = null;
    	
    	// 成本价
        BigDecimal price = BigDecimal.ZERO;
        // 原价欧元
        BigDecimal otPrice = BigDecimal.ZERO;
        // 计算最低价
        for(UnibuyProductSku sku : skus) {
    		price = price.compareTo(new BigDecimal(sku.getCostPrice())) == 1 || price.compareTo(BigDecimal.ZERO) == 0 ? new BigDecimal(sku.getCostPrice()) : price;
            otPrice = otPrice.compareTo(new BigDecimal(sku.getMarketPrice())) == 1 || otPrice.compareTo(BigDecimal.ZERO) == 0 ? new BigDecimal(sku.getMarketPrice()) : otPrice;
        }
        // 加物流费
//        price = StringUtil.isNotEmpty(product.getFreightFee()) ? price.add(new BigDecimal(product.getFreightFee())) : price;

        // PriceResult priceResult = priceUtil.rmb2Eur(otPrice);  old

        //2023.3.22 修改币种获取汇率
        PriceResult priceResult = priceUtil.rmb2Currency(otPrice,supplier);

        if(price.compareTo(BigDecimal.ZERO) == 0) {
        	return null;
        }
        // 大于或小于指定折扣, 原价置空
   	 	boolean discount20 = otPrice.compareTo(BigDecimal.ZERO) == 0 ? false : new BigDecimal("2").compareTo(price.divide(otPrice, 2, RoundingMode.HALF_UP)) <= 0;
   	 	boolean discount1 = otPrice.compareTo(BigDecimal.ZERO) == 0 ? false : new BigDecimal("0.1").compareTo(price.divide(otPrice, 2, RoundingMode.HALF_UP)) >= 0;
        if(-1 == otPrice.compareTo(new BigDecimal("100")) || discount20 || discount1) {
        	priceResult.setPrice(BigDecimal.ZERO);
        }
    	
        // 品牌对应
        StoreBrand storeBrand = storeBrandService.getOne(Wrappers.<StoreBrand>lambdaQuery()
                .eq(StoreBrand :: getOtherId, product.getBrandNo())
                .eq(StoreBrand :: getType, supplier.getIsEurope())
                .last("LIMIT 1")
                );

        if(supplier.getIsEurope()==31){
            storeBrandService.unMatchBrand(storeBrand,product.getBrandNo(),product.getBrandNameEn(),ProductTypeEnum.UNIBUY);
        }else
        {
            storeBrandService.unMatchBrand(storeBrand,product.getBrandNo(),product.getBrandNameEn(),ProductTypeEnum.UNIBUY1);
        }

        if(null != storeBrand && null != storeBrand.getSuperId()) {
            storeBrand = storeBrandService.getById(storeBrand.getSuperId());
        }else {
            storeBrand = storeBrandService.getById(5429);
        }
        
        /***** 处理对象构建 *******/
        String barCode = supplier.getBarcode() + product.getGoodsNo().toString();
        barCode = barCode + "-" + StockAreaTempEnum.getByName(product.getSourceArea()).getTempId();
        List<StoreProductAttr> attrList = new ArrayList<StoreProductAttr>();
        List<StoreProductAttrValueRequest> attrValueList = new ArrayList<StoreProductAttrValueRequest>();
        // 规格
        StoreProductAttr storeProductAttr = new StoreProductAttr();
        storeProductAttr.setAttrName("尺寸");
        storeProductAttr.setType(0);
        // 颜色
        StoreProductAttr storeProductAttrColor = new StoreProductAttr();
        storeProductAttrColor.setAttrName("颜色");
        storeProductAttrColor.setType(0);
        // 轮播图
        String sliderImage = product.getGoodsDetailImage();
        if(CollectionUtils.isEmpty(JSONArray.parseArray(sliderImage))) {
        	sliderImage = JSON.toJSONString(Arrays.asList(product.getGoodsMainImage()));
        }
        
        
        // 合并成suk
        List<String> colorValueList = new ArrayList<String>();
        List<String> valueList = new ArrayList<String>();
        String composition = "";
        for(UnibuyProductSku sku : skus) {
        	composition = sku.getSkuPropertiesName();
            BigDecimal valuePrice = new BigDecimal(sku.getCostPrice());
            // 加物流费
//            valuePrice = StringUtil.isNotEmpty(sku.getFreightFee()) ? valuePrice.add(new BigDecimal(sku.getFreightFee())) : valuePrice;
            StoreProductAttrValueRequest storeProductAttrValueRequest = new StoreProductAttrValueRequest();
            storeProductAttrValueRequest.setSourceSkuId(sku.getSkuNo());
            storeProductAttrValueRequest.setPromotePrice(BigDecimal.ZERO);
            storeProductAttrValueRequest.setPrice(valuePrice);
            storeProductAttrValueRequest.setStock(sku.getQuantity());
            storeProductAttrValueRequest.setBarCode(barCode);

            BigDecimal skuOtPrice = StringUtil.isEmpty(sku.getMarketPrice()) ? BigDecimal.ZERO : new BigDecimal(sku.getMarketPrice());
        	PriceResult skuPriceResult = priceUtil.rmb2Eur(skuOtPrice);

            //2023.3.23 修改币种获取汇率  暂时不使用
//            PriceResult skuPriceResult = priceUtil.rmb2Currency(skuOtPrice,supplier);

            // 大于或小于指定折扣, 原价置空
       	 	boolean discountVal20 = skuOtPrice.compareTo(BigDecimal.ZERO) == 0 ? false : new BigDecimal("2").compareTo(valuePrice.divide(skuOtPrice, 2, RoundingMode.HALF_UP)) <= 0;
       	 	boolean discountVal1 = skuOtPrice.compareTo(BigDecimal.ZERO) == 0 ? false : new BigDecimal("0.1").compareTo(valuePrice.divide(skuOtPrice, 2, RoundingMode.HALF_UP)) >= 0;
        	if(-1 == skuOtPrice.compareTo(new BigDecimal("100")) || discountVal20 || discountVal1) {
        		skuPriceResult.setPrice(BigDecimal.ZERO);
            }
            storeProductAttrValueRequest.setOtPrice(skuPriceResult.getPrice());
            storeProductAttrValueRequest.setCost(valuePrice);
            storeProductAttrValueRequest.setSourceCost(valuePrice);
            storeProductAttrValueRequest.setImage(sku.getGoodsMainImage());

            LinkedHashMap<String, String> linkedMap = new LinkedHashMap<>();
            List<String> suk = new ArrayList<String>();
            linkedMap.put("颜色", "默认");
            if (!colorValueList.contains("默认")) {
                colorValueList.add("默认");
            }
            suk.add("默认");
            String size = sku.getSalePropertiesName().replaceAll("颜色:", "").replaceAll("尺码:", "");
            linkedMap.put("尺寸", size);
            if (!valueList.contains(size)) {
                valueList.add(size);
            }
            
            storeProductAttrValueRequest.setSuk(String.join(",", suk));
            storeProductAttrValueRequest.setAttrValue(linkedMap);
            storeProductAttrValueRequest.setTempId(StockAreaTempEnum.getByName(sku.getSourceArea()).getTempId());
            attrValueList.add(storeProductAttrValueRequest);
        }
        if (CollectionUtils.isNotEmpty(colorValueList)) {
            storeProductAttrColor.setAttrValues(String.join(",", colorValueList));
            attrList.add(storeProductAttrColor);
        }
        if (CollectionUtils.isNotEmpty(valueList)) {
            storeProductAttr.setAttrValues(String.join(",", valueList));
            attrList.add(storeProductAttr);
        }

        productRequest = new StoreProductCrmebRequest();
        productRequest.setExchangeRate(priceResult.getExchangeRate());
        // 抽取所有size属性去重
        productRequest.setAttr(attrList);
        productRequest.setAttrValue(attrValueList);
        // 强制写一个 商户id 作为buyer商品标识标识
//        productRequest.setMerId(CrmebMerchantEnums.UNIBUY.getMerchantId());
        //修改商户id
        productRequest.setMerId(supplier.getMerchantId());
        productRequest.setContent(product.getGoodsPcDesc());
        productRequest.setKeyword(product.getGoodsModel());
        productRequest.setStoreInfo(product.getGoodsPcDesc());
        productRequest.setStoreName(product.getGoodsName());
        productRequest.setBrandId(storeBrand.getId());
        productRequest.setBrandName(storeBrand.getEnName());
        productRequest.setPrice(price);
        productRequest.setOtPrice(priceResult.getPrice());
        productRequest.setCost(price);
        productRequest.setSourceCost(price);
        productRequest.setPromoteFlag(false);
        productRequest.setErpPromFlag(true);

        // 供应商
//        Supplier supplier = supplierService.getOne(Wrappers.<Supplier>lambdaQuery()
//                .eq(Supplier :: getBarcode, BarCodeEnum.UNIBUY.getCode())
//                .last("LIMIT 1")
//                );

        productRequest.setSuppliersId(supplier.getId());
        productRequest.setSuppliersName(supplier.getSuppliersName());
        // 分类
        CategoryMatch categoryMatch = null;
        if(supplier.getIsEurope()==31){
            categoryMatch = categoryMatchService.getOne(Wrappers.<CategoryMatch>lambdaQuery()
                    .eq(CategoryMatch :: getType, CategoryTypeEnum.UNIBUY)
                    .eq(CategoryMatch :: getOthCategoryId, product.getCategoryNo())
                    .last("LIMIT 1")
            );
            categoryMatchService.unMatchCategory(categoryMatch, product.getCategoryNo(), product.getCategoryName(),null,CategoryTypeEnum.UNIBUY);
        }else
        {
            categoryMatch = categoryMatchService.getOne(Wrappers.<CategoryMatch>lambdaQuery()
                    .eq(CategoryMatch :: getType, CategoryTypeEnum.UNIBUY1)
                    .eq(CategoryMatch :: getOthCategoryId, product.getCategoryNo())
                    .last("LIMIT 1")
            );
            categoryMatchService.unMatchCategory(categoryMatch, product.getCategoryNo(), product.getCategoryName(),null,CategoryTypeEnum.UNIBUY1);
        }

        // 复制重量
        if(null != categoryMatch) {
        	CategoryMatch supCategoryMatch = categoryMatchService.getById(categoryMatch.getCategoryId());
        	categoryMatch.setWeight(Optional.ofNullable(supCategoryMatch).orElse(new CategoryMatch()).getWeight());
        }
        Integer categoryId = null != categoryMatch ? categoryMatch.getCategoryId() : 1859;
        productRequest.setBarCode(barCode);
        productRequest.setCateId(categoryId);
        productRequest.setCateIds(Arrays.asList(categoryId));
        productRequest.setWeight(null != categoryMatch ? categoryMatch.getWeight() : BigDecimal.ONE);
        productRequest.setImage(product.getGoodsMainImage());
        productRequest.setSliderImage(sliderImage);
        productRequest.setIsShow(true);
        productRequest.setSort(0);
        productRequest.setSpecType(true);
        productRequest.setComposition(composition);
        productRequest.setIsEurope(supplier.getIsEurope());
        productRequest.setTempId(StockAreaTempEnum.getByName(product.getSourceArea()).getTempId());
        productRequest.setUnitName("件");
        productRequest.setLastPushTime(new Date());
        productRequest.setAddTime(Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)));
        
        return productRequest;
    }

}
